﻿using System.IO;
using log4net;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Web.Mvc;
using System.Linq;
using log4net.Config;

namespace MvcApplication4.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        private readonly Random _r = new Random();
        private const string Names = "Stefan,Stanisław,Mieczysław,Czesław,Zdzisław,Wiesław,Mnięcisław,Krzysztof,Bonawentura,Łafał,Łobełt";
        private const string Surnames = "Marchewa,Płaza,Płażyński,Wójcik,Kotas,Toboła,Owczarek,Rżysko";
        private readonly ILog _log = LogManager.GetLogger("MedicoverLogger");
        //private readonly ILog _log = LogManager.GetLogger(typeof (MvcApplication));
        private int _tranNo = 0;

        public HomeController()
        {
            
        }

        public ActionResult Index()
        {
            string l;
            using(var f = System.IO.File.OpenText(Server.MapPath("~/tran.txt")))
            {
                l = f.ReadToEnd();    
            }
            
            
            if(!string.IsNullOrEmpty(l))
            {
                _tranNo = Convert.ToInt32(l);
                _tranNo++;
            }

            System.IO.File.WriteAllText(Server.MapPath("~/tran.txt"), _tranNo.ToString(CultureInfo.InvariantCulture));

            var n = Names.Split(',');
            var s = Surnames.Split(',');

            var model = new PaymentModel();
            model.Country = "616";
            model.MerchantId = ConfigurationManager.AppSettings["merchantId"];
            // model.OrderNumber = _r.Next(10000, 100000).ToString(CultureInfo.CurrentCulture);
            model.OrderNumber = _tranNo.ToString(CultureInfo.InvariantCulture);
            // model.OrderDescription = "test " + model.OrderNumber;
            model.OrderDescription = "test " + model.OrderNumber;
            model.Amount = _r.Next(1000, 100000).ToString(CultureInfo.CurrentCulture);
            model.Currency = "985";
            model.Name = n[_r.Next(n.Length - 1)];
            model.Surname = s[_r.Next(s.Length - 1)];
            model.Language = "PL";
            model.Autodeposit = "1";
            model.ExpiryTime = "";// EcardDate();
            model.PaymentType = "ALL";
            model.TransparentPages = "1";
            model.Charset = "UTF-8";
            model.LinkFail = string.Format("{0}?",Url.Action("Fail", "Home", null, "http"));
            model.LinkOk = string.Format("{0}?", Url.Action("Ok", "Home", null, "http"));
            model.HashAlgorithm = "MD5";
            model.SessionId = Guid.NewGuid();
            model.Hash = GenerateHash(model);
            model.CreatedDate = DateTime.Now;

            _log.InfoFormat("Creating Ecard form. Serialized data: {0}", Serialize(model));

            return View(model);
        }

        private static string GenerateHash(PaymentModel model)
        {
            var s = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}", model.MerchantId, model.OrderNumber, model.Amount, model.Currency, model.OrderDescription, model.Name, model.Surname, model.Autodeposit, model.PaymentType, model.LinkFail, model.LinkOk, model.ExpiryTime, ConfigurationManager.AppSettings["merchantPassword"]);

            MD5 md5 = new MD5CryptoServiceProvider();
            var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(s));

            var h = hash.Select(p => p.ToString("x2"));
            return string.Join("", h);
        }

        private static string EcardDate()
        {
            var now = DateTime.UtcNow.AddMinutes(5);

            var date = now.ToString("yyyy-MM-ddThh:mm:ssZ");

            return date;
        }

        public ActionResult Fail(string sessionId)
        {
            _log.InfoFormat("Trasanction with ID: {0} failed", sessionId);
            throw new NotImplementedException();
        }

        public ActionResult Ok(string sessionId)
        {
            _log.InfoFormat("Transaction with ID: {0} authorized", sessionId);
            throw new NotImplementedException();
        }

        private static string Serialize(object jsonData)
        {
            var jsonSettings = new JsonSerializerSettings {
            NullValueHandling = NullValueHandling.Include
            };

            return JsonConvert.SerializeObject(jsonData, jsonSettings);
        }

        public string AcceptPayment(FormCollection collection)
        {
            var ecardResponse = Serialize(collection);
            _log.InfoFormat("Response from Ecard: {0}", ecardResponse);

            return "OK";
        }
    }
}
